<template>
  <div class="all">
    <div class="top">
      <el-row>
        <el-form ref="form" inline label-position="left">
          <el-col :span="3">
            <el-form-item label="设备：">
              <Selects v-model="query.equipment_id" action="equipmentList" :query="{ add_field: 'coding' }" refresh />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="设备台账：">
              <el-input v-model="query.equipment_list" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="计划编号：">
              <el-input v-model="query.plan_coding" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="车间：">
              <Selects v-model="query.workshop_id" action="factoryList" :query="{ category: 2 }" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="生产线：">
              <Selects v-model="query.line_id" action="factoryList" :query="{ category: 3 }" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="工位：">
              <Selects v-model="query.process_id" action="factoryList" :query="{ category: 4 }" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="是否停机：">
              <SelfSelect v-model="query.halt" :show-list="YN" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="状 态：">
              <SelfSelect v-model="query.status" :show-list="pmStatus" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="负责人：">
              <Selects v-model="query.admin_id" action="adminList" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="安排时间：">
              <el-date-picker v-model="query.arrange" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="安排时间：">
              <el-date-picker v-model="query.arrange_time" type="datetimerange" range-separator="-" start-placeholder="" end-placeholder="" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item>
              <el-button style="margin-top: 38%" icon="el-icon-search" type="primary" @click="index">查找</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <el-row class="btns">
        <el-button type="primary" icon="el-icon-printer" @click="exportDialog">导出</el-button>
        <el-button v-if="roles.includes('WorkOrderPm5StopApply')" type="primary" icon="el-icon-box" @click="suspend">停产申请</el-button>
        <el-button v-if="roles.includes('WorkOrderPm5StopReview')" type="primary" icon="el-icon-box" @click="suspendReview">停产审核</el-button>
        <el-button v-if="roles.includes('WorkOrderPm5StopReview')" type="primary" icon="el-icon-box" @click="suspendStop">停产驳回</el-button>
        <el-button v-if="roles.includes('WorkOrderPm5Delete')" type="danger" icon="el-icon-delete" @click="delBtn">删除</el-button>
        <el-button type="primary" icon="el-icon-refresh" @click="refresh">刷新</el-button>
      </el-row>
      <span class="total">总数：{{ total }}</span>
    </div>
    <div class="main">
      <div class="table">
        <el-table ref="multipleTable" v-loading="loading" border tooltip-effect="dark" stripe width="100%" :data="dataList" @selection-change="handleSelectionChange">
          <el-table-column label="序号" type="index" align="center" width="50" />
          <el-table-column type="selection" align="center" width="55" />
          <el-table-column prop="plan_coding" label="计划-编号" align="center" width="200" />
          <el-table-column prop="equipment" label="设备名称" align="center" width="200" />
          <el-table-column label="状态" align="center" width="150">
            <template scope="{row}">
              <div v-html="row.status_table" />
            </template>
          </el-table-column>
          <el-table-column prop="line" label="生产线" align="center" width="140" />
          <el-table-column prop="process" label="工位" align="center" />
          <el-table-column prop="task_param_list" label="任务列表" align="left" width="600" />
          <el-table-column prop="member_list" label="执行人" align="center" width="220" />
          <el-table-column prop="admin" label="负责人" align="center" />
          <el-table-column prop="period" label="周期" align="center" />
          <el-table-column prop="period_unit" label="周期单位" align="center" />
          <el-table-column prop="expect_man_minutes" label="期望工时（分钟）" align="center" width="120" />
          <el-table-column prop="actual_man_minutes" label="实际工时（分钟）" align="center" width="120" />
          <el-table-column prop="diff_minutes" label="实际工时与期望工时的差值" align="center" width="170" />
          <el-table-column prop="arrange_time" label="安排时间" align="center" width="160" />
          <el-table-column prop="end_time" label="截止时间" align="center" width="160" />
          <el-table-column prop="qrcode_time" label="扫码时间" align="center" />
          <el-table-column prop="qrcode_admin" label="扫码人（第一次）" align="center" width="120" />
          <el-table-column prop="start_time" label="开始时间" align="center" width="160" />
          <el-table-column prop="submit_complete" label="结束时间" align="center" width="140" />
          <el-table-column prop="workshop" label="车间" align="center" />
          <el-table-column prop="profession" label="专业" align="center" />
          <el-table-column prop="halt" label="是否停机" align="center" />
          <el-table-column prop="category" label="计划分类" align="center" />
          <el-table-column prop="task_long" label="任务时长（小时）" align="center" width="140" />
          <el-table-column prop="delay" label="延时了多少次" align="center" width="120" />
          <el-table-column prop="stop_admin" label="停产人" align="center" />
          <el-table-column prop="status1" label="停产申请之前的状态" align="center" width="160" />
          <el-table-column prop="submit_complete" label="所有读数的提交时间" align="center" width="180" />
          <el-table-column v-if="roles.includes('WorkOrderPm3Detail' || 'WorkOrderPm3Delete')" label="操作" fixed="right" width="180" align="center">
            <template scope="{row}">
              <el-button v-if="roles.includes('WorkOrderPm3Detail')" type="primary" @click="goDetail(row.id)">编辑</el-button>
              <el-button v-if="roles.includes('WorkOrderPm3Delete')" type="danger" @click="handleDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination class="page" background :page-size="query.limit" align="center" layout="total,prev,pager,next,jumper" :total="total" :current-page.sync="query.page" @current-change="index" @size-change="index" />
      </div>
    </div>
    <el-dialog v-loading="isLoading" title="请选择导出字段" :visible.sync="excelDialog" width="60%" :element-loading-text="loadingExcel" element-loading-spinner="el-icon-loading">
      <div>
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
        <div style="margin: 15px 0;"></div>
        <el-checkbox-group v-model="needExport" @change="handleCheckedCitiesChange">
          <el-checkbox v-for="title in tableHead" class="checkStyle" :label="title" :key="title"></el-checkbox>
        </el-checkbox-group>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="excelDialog = false">取 消</el-button>
        <el-button type="primary" @click="exportExcel">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import API from '@/api/workorder/pm'
import { pmStatus, YN } from '@/utils/option'
import Selects from '@/components/select-search'
import SelfSelect from '@/components/select-o'
import XLSX from 'xlsx'
import { pmsTables } from '@/utils/Table'
import { mapGetters } from 'vuex'
const tableOptions = ['计划-编号', '设备编号', '设备名称', '状态', '车间', '生产线', '工位', '存放位置', '任务', '执行人', '负责人', '周期', '周期单位', '安排时间', '扫码时间', '扫码人（第一次）', '开始时间', '结束时间', '期望工时（分钟）', '实际工时（分钟）', '实际工时与期望工时的差值', '截止时间', '任务时长（小时）', '专业', '是否停机', '计划分类', '延时了多少次）', '停产人', '停产申请之前的状态']
export default {
  components: {
    SelfSelect,
    Selects
  },
  inject: ['goUrl', 'reload'],
  data() {
    return {
      dataList: [],
      total: 0,
      loading: true,
      query: {
        limit: 15,
        page: 1,
        plan_category: 5
      },
      pmStatus,
      isLoading: false,
      loadingExcel: '正在导出...',
      YN,
      exportList: [],
      excelDialog: false,
      needExport: ['计划-编号', '设备编号', '设备名称', '状态', '车间', '生产线', '工位', '存放位置', '任务', '执行人', '负责人', '周期', '周期单位', '安排时间', '扫码时间', '扫码人（第一次）', '开始时间', '结束时间', '期望工时（分钟）', '实际工时（分钟）', '实际工时与期望工时的差值', '截止时间', '任务时长（小时）', '专业', '是否停机', '计划分类', '延时了多少次）', '停产人', '停产申请之前的状态'],
      isIndeterminate: true,
      tableHead: tableOptions,
      checkAll: true,
      pmsTables,
      multipleSelection: []
    }
  },
  created() {
    const query = JSON.parse(sessionStorage.getItem('pm5'))
    if (query) {
      this.query = query
      sessionStorage.removeItem('pm5')
      this.index()
    } else {
      this.index()
    }
    window.addEventListener('keydown', this.handKeyCode, true)
  },
  computed: {
    ...mapGetters(['roles']),
    pages() {
      return this.total / 1000 + 1
    }
  },
  methods: {
    index() {
      this.loading = true
      API.getList(this.query).then(res => {
        this.dataList = []
        this.dataList = res.data.list.data
        this.total = res.data.list.total
      }).finally(() => {
        this.loading = false
      })
    },
    handKeyCode(e) {
      if(e.keyCode === 13 || e.keyCode === 32){//回车搜索
        this.index()
      }
    },
    setStorage() {
      sessionStorage.setItem('pm5', JSON.stringify(this.query))
    },
    goDetail(id) {
      this.setStorage()
      const url = `/workOrder/pm5/edit/${id}`
      this.goUrl(url)
    },
    handleAdd() {
      this.setStorage()
      this.goUrl('/workOrder/pm5/add')
    },
    refresh() {
      this.reload()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleDel(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        API.delete(id).then(res => {
          if (res.data.error_code !== 1) {
            this.$message.error(res.data.message)
          } else {
            this.setStorage()
            this.$message.success('删除成功')
            this.index()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    delBtn() {
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        const idArray = []
        this.multipleSelection.forEach(item => {
          idArray.push(item.id)
        })
        const id = idArray.join(',')
        this.handleDel(id)
      } else {
        this.$message('请先选择，然后再删除')
      }
    },
    suspend() {
      this.loading = true
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        const idArray = []
        this.multipleSelection.forEach(item => {
          idArray.push(item.id)
        })
        const id = idArray.join(',')
        console.log(id, 665)
        API.suspend({ id }).then(res => {
          if (res.data.error_code !== 1) {
            this.$message.error(res.data.message)
            this.loading = false
          } else {
            this.$message.success('操作成功')
            this.loading = false
            this.index()
          }
        })
      } else {
        this.suspendAll()
      }
    },
    suspendAll() {
      const idArray = []
      this.query.limit = this.total
      this.query.page = null
      API.getList(this.query).then(res => {
        this.suspendList = res.data.list.data
        this.suspendList.forEach(item => {
          idArray.push(item.id)
        })
      }).finally(() => {
        const id = idArray.join(',')
        API.suspend({ id }).then(res => {
          if (res.data.error_code !== 1) {
            this.$message.error(res.data.message)
            this.loading = false
          } else {
            this.$message.success('操作成功')
            this.loading = false
            this.index()
          }
        })
      })
    },
    suspendReview() {
      this.loading = true
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        const idArray = []
        this.multipleSelection.forEach(item => {
          idArray.push(item.id)
        })
        const id = idArray.join(',')
        API.SuspendReview({ id, suspend: 1 }).then(res => {
          if (res.data.error_code !== 1) {
            this.$message.error(res.data.message)
          } else {
            this.$message.success('操作成功')
            this.index()
          }
        })
      } else {
        this.suspendReviewAll()
      }
    },
    suspendReviewAll() {
      const idArray = []
      this.query.limit = this.total
      this.query.page = null
      API.getList(this.query).then(res => {
        this.suspendList = res.data.list.data
        this.suspendList.forEach(item => {
          idArray.push(item.id)
        })
      }).finally(() => {
        const id = idArray.join(',')
        API.SuspendReview({ id, suspend: 1 }).then(res => {
          if (res.data.error_code !== 1) {
            this.$message.error(res.data.message)
            this.loading = false
          } else {
            this.$message.success('操作成功')
            this.loading = false
            this.index()
          }
        })
      })
    },
    suspendStop() {
      this.loading = true
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        const idArray = []
        this.multipleSelection.forEach(item => {
          idArray.push(item.id)
        })
        const id = idArray.join(',')
        API.SuspendReview({ id, suspend: 2 }).then(res => {
          if (res.data.error_code !== 1) {
            this.$message.error(res.data.message)
          } else {
            this.$message.success('操作成功')
            this.index()
          }
        })
      } else {
        this.suspendStopAll()
      }
    },
    suspendStopAll() {
      const idArray = []
      this.query.limit = this.total
      this.query.page = null
      API.getList(this.query).then(res => {
        this.suspendList = res.data.list.data
        this.suspendList.forEach(item => {
          idArray.push(item.id)
        })
      }).finally(() => {
        const id = idArray.join(',')
        API.SuspendReview({ id, suspend: 2 }).then(res => {
          if (res.data.error_code !== 1) {
            this.$message.error(res.data.message)
            this.loading = false
          } else {
            this.$message.success('操作成功')
            this.loading = false
            this.index()
          }
        })
      })
    },
    exportDialog() {
      this.excelDialog = true
    },
    handleCheckAllChange(val) {
      this.needExport = val ? tableOptions : []
      this.isIndeterminate = false
    },
    handleCheckedCitiesChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.tableHead.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.tableHead.length
    },
    toExcel() {
      const exportData = []
      const exportTitle = []
      const titleObj = this.pmsTables
      exportData.push(this.needExport)
      for (const keys of this.needExport) {
        exportTitle.push(Object.keys(titleObj).find(key => titleObj[key] === keys))
      }
      this.exportList.forEach(item => {
        const arr = []
        for (const key of exportTitle) {
          arr.push(item[key])
        }
        exportData.push(arr)
      })
      const ws = XLSX.utils.aoa_to_sheet(exportData)
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
      /* save to file */
      this.loading = false
      this.excelDialog = false
      XLSX.writeFile(wb, '专业点检.xlsx')
      this.isLoading = false
    },
    async getExcel(condition) {
      this.exportList = []
      const res = await API.getList(condition)
      const exportList = res.data.list.data
      const total = res.data.list.total
      this.exportList.push(...exportList)
      if (this.exportList.length === total) {
        this.isLoading = false
        this.toExcel()
      }
    },
    allExcel() {
      this.isLoading = true
      const arr = Object.keys(this.query)
      const len = arr.length
      console.log(len)
      if (len > 8 || this.query.manufacturer_id || this.query.equipment_id || this.query.line_id || this.query.process_id || this.query.workshop_id) {
        console.log('带条件的导出')
        const condition = this.query
        condition.limit = this.total
        condition.page = 1
        this.getExcel(condition)
      } else {
        for (let i = 1; i <= this.pages; i++) {
          const condition = {
            limit: 1000,
            page: i,
            plan_category: 5
          }
          this.getExcel(condition)
        }
      }
    },
    exportExcel() {
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        this.exportList = this.multipleSelection
        this.toExcel()
      } else {
        this.allExcel()
      }
    }
  }
}
</script>
